package cn.tmpan.project.utils;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;

import java.io.File;


/**
 * @Author pantiemin
 * @Desc: Description code
 * @Date 2018/11/30 11:23
 */
@Slf4j
public class QiNiuCosClientUtil {

    /**
     * 获取上传文件的token
     *
     * @param isTemp 是否临时token 默认有效时间 3600s
     * @return
     */
    public static String getUpToken(Boolean isTemp) {
        Auth auth = Auth.create(PropertiesUtil.getProperty("AccessKey"), PropertiesUtil.getProperty("SecretKey"));
        if (isTemp) {
            return auth.uploadToken(PropertiesUtil.getProperty("BUCKET"), null, Long.parseLong(PropertiesUtil.getProperty("EX_TIME")), new StringMap());
        }
        return auth.uploadToken(PropertiesUtil.getProperty("BUCKET"));
    }


    /**
     * 上传文件到七牛云对象存储空间
     *
     * @param localFilePath
     * @param fileName
     * @return
     */
    public static String uploadFileToServer(String localFilePath, String fileName) {
        String token = getUpToken(false);
        try {
            Response response = getUploadManager().put(localFilePath, fileName, token);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;

        } catch (QiniuException e) {
            log.error("文件上传到七牛云服务器失败!:{}", e.getMessage());
            return null;
        }
    }

    /**
     * 上传文件到七牛服务器
     *
     * @param localFile
     * @param fileName
     * @return
     */
    public static String uploadFileToServer(File localFile, String fileName) {

        String token = getUpToken(false);
        try {
            Response response = getUploadManager().put(localFile, fileName, token);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;

        } catch (QiniuException e) {
            log.error("文件上传到七牛云失败!:{}", e.getMessage());
            return null;
        }
    }

    /**
     * 获取文件上传执行对象
     *
     * @return
     */
    private static UploadManager getUploadManager() {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());

        UploadManager uploadManager = new UploadManager(cfg);
        return uploadManager;
    }
}
